<?php
namespace app\common\service;

use think\Model;
use app\common\model\Tag;
use app\common\model\TagUser;

class TagService extends Model
{
    /**
     * 常用标签
     * @param TagUser $tuModel
     * @param int $sid
     * @param int $uid
     * @param int $num
     */
    public function getCommonTagList(TagUser $tuModel,$sid,$uid,$num){
        $where=[
            'tu.store_id'=>$sid,
            'tu.create_uid'=>$uid
        ];
        $list=db()->name('tag_user')->alias('tu')
            ->join('tag t','tu.tag_id = t.tag_id')
            ->where($where)
            ->group('tu.tag_id')
            ->order("count('tu.tag_id') DESC")
            ->field("tu.tag_id,count('tu.tag_id') as tag_num,t.tag_name,t.user_id as type")
            ->limit($num)
            ->select();
        

        return $list;
    }
    /**
     * 客户标签
     * @param int $sid
     * @param int $cid
     * @param int $type 1-顾问打的标签，2-客户自己给自己打的标签
     */
    public function getUserTagList($sid, $cid, $type = 1, $student_id = 0){
        $where=[
            'tu.store_id'=>$sid
//            'tu.uid'=>$cid
        ];
        if($student_id > 0){
            $where['tu.student_id'] = $student_id;
        } else {
            $where['tu.uid'] = $cid;
        }

        if($type == 1){
            $where['create_uid'] = ['neq',$cid];
        }else{
            $where['create_uid'] = $cid;
        }
        $list=db()->name('tag_user')->alias('tu')
            ->join('tag t','tu.tag_id = t.tag_id')
            ->where($where)
            ->order("tu.addtime desc")
            ->field("tu.tag_id,tu.tag_name,t.user_id as type")
            ->select();

        return $list;
    }

    public function getUserTagListNew2($sid, $cid, $student_id, $type = 1){
        $where=[
            'tu.store_id'=>$sid
        ];
        if($student_id){
            $where['tu.student_id'] = $student_id;
        } else {
            $where['tu.uid'] = $cid;
        }

        if($type == 1){
            $where['tu.create_uid'] = ['neq',$cid];
        }else{
            $where['tu.create_uid'] = $cid;
        }
        $list=db()->name('tag_user')->alias('tu')
            ->join('tag t','tu.tag_id = t.tag_id')
            ->where($where)
            ->order("tu.addtime desc")
            ->field("tu.tag_id,tu.tag_name,t.user_id as type")
            ->select();

        return $list;
    }

    public function getUserTagListNew($sid, $cid, $student_id, $type = 1){
        $where=[
            'tu.store_id'=>$sid
        ];
        if($student_id){
            $where['tu.student_id'] = $student_id;
        } else {
            $where['tu.uid'] = $cid;
        }

        if($type == 1){
            $where['create_uid'] = ['neq',$cid];
        }else{
            $where['create_uid'] = $cid;
        }
        $list=db()->name('tag_user')->alias('tu')
            ->join('tag t','tu.tag_id = t.tag_id')
            ->where($where)
            ->order("tu.addtime desc")
            ->field("tu.tag_id,tu.tag_name,t.user_id as type")
            ->select();


        return $list;
    }


    /**
     * 微信端: 获取用户访问学员的兴趣标签列表
     * @param $sid
     * @param $studentsid
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function userAccessStudentsTagList($sid, $studentsid){
        $students_uid = db('students')->where(['sid' => $sid, 'id' => $studentsid, 'status' => 1, 'is_counselor' => 0])->value('uid');
        if(!$students_uid){
            return false;
        }
        //用户自己添加的兴趣标签
        return $this->getUserTagList($sid, $students_uid, 2);
    }


    /**
     * 顾问自定义标签
     * @param TagUser $tuModel
     * @param int $sid
     * @param int $uid
     */
    public function getUserDefinedTagList(Tag $tagModel,$sid,$uid){
        $where=[
            'store_id'=>$sid,
            'user_id'=>$uid
        ];
        $list=$tagModel::all($where);
       
        return $list;
    }

    /**
     * 系统标签
     * @param TagUser $tuModel
     * @param int $sid
     */
    public function getSystemTagList(Tag $tagModel,$sid,$type){
        if($type > 0){
            $where_in = [0,$type];
        }else{
            $where_in = [0];
        }
        $where=[
            't.store_id'=>$sid,
            't.user_id'=>0
        ];
        $list=db()->name('tag')->alias('t')
            ->join('tag_class tc','t.tag_classid = tc.class_id')
            ->where($where)
            ->whereIn('tc.use_scene',$where_in)
            ->order('t.addtime desc')
            ->field('t.tag_id,t.tag_name,tc.class_id,tc.class_name')
            ->select();
        if(!$list){
            return null;
        }else{
            $tag_list=array();
            foreach($list as $v){
                $tag_list[$v['class_id']]['class_id']=$v['class_id'];
                $tag_list[$v['class_id']]['class_name']=$v['class_name'];
                $tag_list[$v['class_id']]['tag'][]=array('tag_id'=>$v['tag_id'],'tag_name'=>$v['tag_name']);
            }
            $tag_list_end=array();
            foreach($tag_list as $v){
                $tag_list_end[]=$v;
            }
        }
        return $tag_list_end;
    }

    /**
     * 添加标签
     * @param Tag $tagModel
     * @param int $sid
     * @param int $uid
     * @param int $tag_name
     */
    public function addTagRecord(Tag $tagModel,$sid,$uid,$tag_name){
        //查找该标签是否已经存在
        $tag_info=$tagModel::whereLike('tag_name',$tag_name)->where(['user_id'=>$uid,'store_id'=>$sid])->field('tag_id')->find();
        if($tag_info['tag_id']>0){
            return $tag_info['tag_id'];
        }
        $data=[
            'store_id'=>$sid,
            'user_id'=>$uid,
            'tag_name'=>$tag_name,
            'tag_classid'=>0,
            'addtime'=>time()
            ];
        $res = $tagModel->insertGetId($data);
        return $res;
    }
    /**
     * 绑定标签
     * @param Tag $tagModel
     * @param Tag $tuModel
     * @param int $sid
     * @param int $uid
     * @param int $cid
     * @param int $tid
     */
    public function selectTagRecord(Tag $tagModel,TagUser $tuModel,$sid,$uid,$cid,$tid){
        //清除前顾问打的标签
        $former = $tuModel::where(['uid' => $cid,'create_uid'=>['neq',$uid],'store_id'=>$sid])->find();
        if(!empty($former)){
            $tuModel::where(['uid' => $cid,'create_uid'=>['neq',$uid],'store_id'=>$sid])->delete();
        }
        //查找该标签是否已经存在
        $tag_info=$tagModel::where('tag_id',$tid)->field('tag_id,tag_name')->find();
        if($tag_info['tag_id']<0){
            return false;
        }
        //查找该条记录是否存在
        $tag_user_info=$tuModel::where(['uid'=>$cid,'tag_id'=>$tid])->find();
        if($tag_user_info){
            return false;   
        }
        $data=[
            'store_id'=>$sid,
            'create_uid'=>$uid,
            'uid'=>$cid,
            'tag_id'=>$tid,
            'tag_name'=>$tag_info['tag_name'],
            'addtime'=>time()
            ];
        $res = $tuModel->insertGetId($data);
        return $res;
    }

    public function selectTagRecordNew(Tag $tagModel, TagUser $tuModel, $sid, $uid, $cid, $student_id, $tid){
        //清除前顾问打的标签
        $former = $tuModel::where(['uid' => $cid,'create_uid'=>['neq',$uid],'store_id'=>$sid])->find();
        if(!empty($former)){
            $tuModel::where(['uid' => $cid,'create_uid'=>['neq',$uid],'store_id'=>$sid])->delete();
        }
        //查找该标签是否已经存在
        $tag_info=$tagModel::where('tag_id',$tid)->field('tag_id,tag_name')->find();
        if($tag_info['tag_id']<0){
            return false;
        }
        //查找该条记录是否存在
        $tag_user_info=$tuModel::where(['uid'=>$cid,'tag_id'=>$tid])->find();
        if($tag_user_info){
            return false;
        }
        $data=[
            'store_id'=>$sid,
            'create_uid'=>$uid,
            'uid'=>$cid ?? 0,
            'tag_id'=>$tid,
            'tag_name'=>$tag_info['tag_name'],
            'addtime'=>time(),
            'student_id' => $student_id
        ];
        $res = $tuModel->insertGetId($data);
        return $res;
    }



    /**
     * 解绑标签
     * @param Tag $tagModel
     * @param Tag $tuModel
     * @param int $sid
     * @param int $uid
     * @param int $cid
     * @param int $tid
     */
    public function unbindTagRecord(Tag $tagModel,TagUser $tuModel,$sid,$uid,$cid,$tid){
        $where=[
            'store_id'=>$sid,
            'create_uid'=>$uid,
            'uid'=>$cid,
            'tag_id'=>$tid,
            ];
        //查找该条记录是否存在
        $tag_user_info=$tuModel::where($where)->find();
        if(!$tag_user_info){
            return false;   
        }
        
        $res = $tuModel->where($where)->delete();
        return $res;
    }

    public function unbindTagRecordNew(Tag $tagModel,TagUser $tuModel, $sid, $uid, $cid, $student_id, $tid){
        $where=[
            'store_id' => $sid,
            'create_uid' => $uid,
            'tag_id' => $tid,
        ];
        if($cid){
            $where['uid'] = $cid;
        } else {
            $where['student_id'] = $student_id;
        }

        //查找该条记录是否存在
        $tag_user_info=$tuModel::where($where)->find();
        if(!$tag_user_info){
            return false;
        }

        $res = $tuModel->where($where)->delete();
        return $res;
    }


    /**
     * 添加标签分类
     * @param $sid
     * @param $class_name
     * @param $use_scene
     * @return int|string
     */
    public function addTagClass($sid, $class_name, $use_scene){
        $data = [
            'store_id' => $sid,
            'class_name' => $class_name,
            'use_scene' => $use_scene,
            'addtime' => time()
        ];
        return db('tag_class')->insert($data);
    }


    /**
     * 编辑标签分类
     * @param $sid
     * @param $class_id
     * @param $class_name
     * @param $use_scene
     * @return int|string
     * @throws \think\Exception
     */
    public function editTagClass($sid, $class_id, $class_name, $use_scene){
        //查询当前标签使用情况
        $info = $this->getUserUseTagClass($sid, $class_id);
        if($info){
            return ['status' => 0, 'msg' => '当前标签分类正在使用，无法编辑'];
        }
        //更新
        $result = $this->updateTagClass($sid, $class_id, $class_name, $use_scene);
        return $result === false ? ['status' => 0, 'msg' => '编辑失败'] : ['status' => 1, 'msg' => '编辑成功'];
    }

    /**
     * 更新标签分类
     * @param $sid
     * @param $class_id
     * @param $class_name
     * @param $use_scene
     * @return int|string
     * @throws \think\Exception
     */
    public function updateTagClass($sid, $class_id, $class_name, $use_scene){
        $data = [
            'class_name' => $class_name,
            'use_scene' => $use_scene,
            'addtime' => time()
        ];
        return db('tag_class')->where(['class_id' => $class_id, 'store_id' => $sid])->update($data);
    }

    /**
     * 获取某标签分类用户使用情况
     * @param $sid
     * @param $class_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getUserUseTagClass($sid, $class_id){
        $result = db()->name('tag_class')
                    ->alias('tc')
                    ->join('tag t', 'tc.class_id = t.tag_classid')
                    ->join('tag_user tu', 't.tag_id = tu.tag_id')
                    ->where(['tc.store_id' => $sid, 'tc.class_id' => $class_id])
                    ->select();
        return $result;
    }

    /**
     * 删除标签分类
     * @param $sid
     * @param $class_id
     * @return array|int
     * @throws \think\Exception
     */
    public function deleteTagClass($sid, $class_id){
        $info = $this->getUserUseTagClass($sid, $class_id);
        if($info){
            return ['status' => 0, 'msg' => '当前标签分类正在使用，无法删除'];
        }
        $result = db('tag_class')->where(['store_id' => $sid, 'class_id' => $class_id])->delete();
        return $result === false ? ['status' => 0, 'msg' => '删除失败'] : ['status' => 1, 'msg' => '删除成功'];
    }

    /**
     * 获取标签分类列表
     * @param $sid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getTagClassList($sid){
        $list_count = db('tag_class')->where(['store_id' => $sid])->count();
        $list = db('tag_class')->where(['store_id' => $sid])->select();
        if($list){
            foreach($list as $k => $v){
                $list[$k]['addtime'] = date('Y-m-d', $v['addtime']);
            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];
    }


    /**
     * 【后台】获取系统标签列表
     * @param $sid
     * @param $use_scene
     * @param $class_name
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getSysTagList($sid, $use_scene, $class_name, $p, $pageSize)
    {
        /*$where = [];
        $where['tc.store_id'] = $sid;
        if (!empty($use_scene)) {
            $where['tc.use_scene'] = $use_scene;
        }
        if (!empty($class_name)) {
            $where['tc.class_name'] = $class_name;
        }

        $field = 'tc.*,t.tag_id,t.tag_name';
        $list = db()->name('tag_class')
                ->alias('tc')
                ->field($field)
                ->join('tag t', 't.tag_classid = tc.class_id','LEFT')
                ->where($where)
                ->order('tc.class_id DESC')
                ->select();

        $data = [];
        $d = [];
        if($list){
            foreach($list as $k => $v){
                if(!isset($data[$v['class_id']])){
                    $data[$v['class_id']] = [
                        'class_id' => $v['class_id'],
                        'class_name' => $v['class_name'],
                        'use_scene' => $v['use_scene'],
                        'addtime' => date('Y-m-d', $v['addtime'])
                    ];
                }
                if($v['tag_id']){
                    $data[$v['class_id']]['tag_list'][] = [
                        'tag_id' => $v['tag_id'],
                        'tag_name' => $v['tag_name']
                    ];
                } else {
                    $data[$v['class_id']]['tag_list'] = [];
                }

            }
            //因接口返回数据不是数组对象，故重新赋值给一个数组变量即可
            foreach($data as $value){
                $d[] = $value;
            }
        }

        return $d;*/
        $where = [];
        $where['store_id'] = $sid;
        if (!empty($use_scene)) {
            $where['use_scene'] = ['like', "%$use_scene%"];
        }
        if (!empty($class_name)) {
            $where['class_name'] = ['like', "%$class_name%"];
        }
        $list_count = db('tag_class')->where($where)->count();
        $class_list = db('tag_class')->where($where)->order('addtime DESC')->limit(($p -1)*$pageSize, $pageSize)->select();
        if($class_list){
            foreach($class_list as $k => $v){
                $class_list[$k]['tag_list'] = db('tag')
                                                ->field('tag_id,tag_name')
                                                ->where(['tag_classid' => $v['class_id'], 'store_id' => $sid, 'user_id' => 0])
                                                ->order('addtime DESC')
                                                ->select();
            }
        }
        return ['content' => $class_list,'page' =>['count' =>$list_count]];
    }

    /**
     * 新增或修改系统标签
     * @param $sid
     * @param $tag_id
     * @param $tag_name
     * @param $tag_classid
     * @return int|string
     * @throws \think\Exception
     */
    public function saveSystemTag($sid, $tag_id, $tag_name, $tag_classid){
        if($tag_id > 0){
            return db('tag')->where(['tag_id' => $tag_id, 'store_id' => $sid])->setField('tag_name',$tag_name);
        } else {
            $data = [
                'tag_classid' => $tag_classid,
                'tag_name' => $tag_name,
                'store_id' => $sid,
                'user_id' => 0,
                'addtime' => time()
            ];
            return db('tag')->insert($data);
        }
    }

    /**
     * 删除标签
     * @param $sid
     * @param $tag_id
     * @return array
     * @throws \think\Exception
     */
    public function deleteTag($sid, $tag_id){
        //查询该标签是否正在使用
        $info = db('tag_user')->where(['tag_id' => $tag_id, 'store_id' => $sid])->find();
        if($info){
            return ['status' => 0, 'msg' => '该标签有用户正在使用，无法删除'];
        }

        $result = db('tag')->where(['tag_id' => $tag_id, 'store_id' => $sid])->delete();
        return $result === false ? ['status' => 0, 'msg' => '删除失败'] : ['status' => 1, 'msg' => '删除成功'];
    }

    /**
     * 获取用户自定义标签列表
     * @param $sid
     * @param $tag_name
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getUseDefinedTagList($sid, $tag_name, $p, $pageSize){
        $where = [];
        $where['t.store_id'] = $sid;
        $where['t.user_id'] = ['>', 0];
        if(!empty($tag_name)){
            $where['t.tag_name'] = ['like', "%$tag_name%"];
        }
        $list_count = db()->name('tag')
                        ->alias('t')
                        ->join('user u', 't.user_id = u.user_id')
                        ->join('tag_user tu', 't.tag_id = tu.tag_id', 'LEFT')
                        ->where($where)
                        ->count();
        $field = 'u.user_nickname,t.*,tu.uid as using_user_id';
        $list = db()->name('tag')
                ->alias('t')
                ->field($field)
                ->join('user u', 't.user_id = u.user_id')
                ->join('tag_user tu', 't.tag_id = tu.tag_id', 'LEFT')
                ->where($where)
                ->order('t.addtime DESC')
                ->limit(($p-1)*$pageSize, $pageSize)
                ->select();

//        $list = db()->name('tag')
//            ->alias('t')
//            ->field($field)
//            ->join('user u', 't.user_id = u.user_id')
//            ->where($where)
//            ->order('t.addtime DESC')
//            ->limit(($p-1)*$pageSize, $pageSize)
//            ->select();
//
//        if($list){
//            foreach($list as $k => $v){
//                $list[$k]['using_count'] = db('tag_user')->where(['tag_id' => $v['tag_id'], 'create_uid' => $v['user_id']])->count();
//            }
//        }
        $data = [];
        $d = [];
        if($list){
            foreach($list as $k => $v){
                if(!isset($data[$v['tag_id']])){
                    $data[$v['tag_id']] = [
                        'tag_id' => $v['tag_id'],
                        'user_id' => $v['user_id'],
                        'tag_name' => $v['tag_name'],
                        'user_nickname' => $v['user_nickname'],
                        'addtime' => date('Y-m-d',$v['addtime']),
                    ];
                }
                if($v['using_user_id']){
                    $data[$v['tag_id']]['using_list'][] = $v['using_user_id'];
                }
                $data[$v['tag_id']]['using_count'] = isset($data[$v['tag_id']]['using_list']) ? count($data[$v['tag_id']]['using_list']) : 0;
            }
            foreach ($data as $value) {
                $d[] = $value;
            }
        }
        return ['content' => $d,'page' =>['count' =>$list_count]];
    }
}